package com.ssm.spring.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * Author  zxy
 * Date  2022/11/11 下午 4:20
 */
public class ProxyFactory {

    private Object target;

    public ProxyFactory(Object target) {
        this.target = target;
    }

    public Object getProxy() {
        // 类加载器
        ClassLoader classLoader = this.getClass().getClassLoader();
        // 得到全部的接口
        Class<?>[] interfaces = target.getClass().getInterfaces();
        // 得到InvocationHandler接口的子类实例
        InvocationHandler h = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) {
                Object result = null;
                try {
                    System.out.println("日志，方法：" + method.getName() + ",参数：" + Arrays.toString(args));
                    result = method.invoke(target, args);
                    System.out.println("日志，方法：" + method.getName() + ",结果：" + result);
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("日志，方法：" + method.getName() + ",异常" + e);
                } finally {
                    System.out.println("日志，方法：" + method.getName() + ",方法执行完毕");
                }
                return result;
            }
        };
        // 返回实现了目标类接口的代理类实例
        return Proxy.newProxyInstance(classLoader, interfaces, h);
    }

}
